package gl.android.jxzs;

import gl.android.jxzs.event.EventNewMessage;
import gl.android.jxzs.socket.Client;
import gl.android.jxzs.socket.MessageHandler;
import gl.common.UserManger;
import gl.uitls.Lg;

import java.io.IOException;
import java.net.UnknownHostException;

import org.json.JSONObject;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import de.greenrobot.event.EventBus;

public class PushService extends Service {
	public PushService() {
	}

	final String ip = "120.198.105.94";
	final int port = 65011;
	static int interval = 3 * 60 * 1000;// 3 minuter

	boolean isReceiveMessageComplete = false;
	private MessageHandler mMessageHandler = new MessageHandler() {
		public void handle(String content) {
			isReceiveMessageComplete = true;
			if (content == null) {
				System.out.println("packet is null");
				return;
			}
			System.out.println("receive:" + content);
			JSONObject jo;
			try {
				jo = new JSONObject(content);
//				jo = new JSONObject("{\"code\":\"0\",\"title\":\"通知\",\"desc\":\"通知：刘凯测试的通知\",\"smstypes\":\"2,4\"}");
				if (!"0".equals(jo.opt("code"))) {
					return;
				}
				// TODO 保存消息
				// TODO 发布通知到通知栏
				// TODO 发送新消息的广播
				EventBus.getDefault().post(new EventNewMessage(jo));
				MessageNotification.notify(getBaseContext(),
						jo.optString("title"), jo.optString("desc"),content, 0);
			} catch (Exception e) {
				e.printStackTrace();
			}

		};
	};

	@Override
	public IBinder onBind(Intent intent) {
		throw new UnsupportedOperationException("Not yet implemented");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Lg.i(this, "onStartCommand" + "flag" + flags + "startId" + startId);
		startLoopTask();
		// We want this service to continue running until it is explicitly
		// stopped, so return sticky.
		return START_STICKY;
	}

	private boolean flag_getNewMessageLoop = false;
	private Thread Thread_getNewMessageLoop;

	private void startLoopTask() {

		if (TextUtils.isEmpty(UserManger.getInstance().username)) {
			// user name is null,please try again after login
			Lg.e(this, "username is null,please try again after login");
			stopServer();
			return;
		}
		if (flag_getNewMessageLoop) {
			Lg.e(this, "loopTask had start,ignore this method invoke");
			// loopTask had start,ignore this method invoke
			return;
		}
		Thread_getNewMessageLoop = new Thread() {
			public void run() {
				flag_getNewMessageLoop = true;
				try {
					while (flag_getNewMessageLoop) {
						Client client = new Client();
						try {
							client.setMessageHandler(mMessageHandler);
							client.connect(ip, port);
							sleep(300);
							Lg.i(this, "Scoket connect" + "ip" + ip + "port"
									+ port);
							int length = 4 + 6 + UserManger.getInstance().username
									.length();
							isReceiveMessageComplete = false;
							client.sendMessage(String.format("%04d010001%s",
									length, UserManger.getInstance().username));

							int timeout = 10 * 1000;
							long current = System.currentTimeMillis();
							while (System.currentTimeMillis() - current < timeout
									&& !isReceiveMessageComplete) {
								sleep(1000);
							}

							client.disConnect();
							client = null;
						} catch (UnknownHostException e) {
							e.printStackTrace();
							client.disConnect();
						} catch (IOException e) {
							e.printStackTrace();
							client.disConnect();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}

						sleep(interval);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
					flag_getNewMessageLoop = false;
					stopServer();
				}
			};
		};
		Thread_getNewMessageLoop.start();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		stopServer();
		Lg.i(this, "onDestory");
	}

	private void stopServer() {
		if (Thread_getNewMessageLoop != null) {
			Thread_getNewMessageLoop.interrupt();
		}
	}

}
